import {Component, ElementRef, OnInit} from "@angular/core";
import {ActivatedRoute, Router} from "@angular/router";
import {NzMessageService} from "ng-zorro-antd";
import {FetchService} from "../../../core/net/fetch.service";
import {FormBuilder, FormGroup} from "@angular/forms";
import {format} from "date-fns";
import {DomSanitizer, SafeResourceUrl} from "@angular/platform-browser";
import {Rect, Topology} from "topology-core";
import {Options} from "topology-core/options";
import * as _ from "lodash";

@Component({
  selector: 'app-dispatch-sh',
  templateUrl: './dispatch-sh.component.html',
  styleUrls: ['../dispatch-common.scss', './dispatch-sh.component.scss']
})
export class DispatchShComponent implements OnInit {
  nzBodyStyle: any = {
    padding: '16px 20px'
  };
  applyModalShow = false;
  applyAmount: number;
  applyForm: FormGroup;
  recordModalShow = false;
  dutyRecordModalShow = false;
  dataList: any[] = [];


  jskllModalShow = false;
  gqjskllReportSrc: SafeResourceUrl;
  zxData;
  rect: Rect;
  canvas: Topology;
  canvasOptions: Options = {};
  hoverItem = {
    top: '0px',
    left: '0px',
    alertLevel: '-',
    waterLevel: '-',
    limitTraffic: '-',
    flow: '-'
  };
  infoShow = false;

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private fetchService: FetchService,
    private el: ElementRef,
    private sanitizer: DomSanitizer
  ) {
    this.applyForm = this.fb.group({
      id: [null],
      startType: [1],
      applyLargeUnit: [0],
      applySmallUnit: [0],
      addType: [1],
      addNum: [0],
      applyTime: [null],
      remark: [null]
    });
  }

  ngOnInit(): void {
    // this.getApplyObject();
    window.addEventListener('resize', this.debounce(() => {
      this.onResize();
    }, 500));
    this.getMapData();
    this.queryGqjskll();
  }


  // 防抖函数
  debounce(func, wait?, immediate?): any {
    let timeout;
    return function() {
      const context = this;
      const args = arguments;
      const later = () => {
        timeout = null;
        if (!immediate) {
          func.apply(context, args);
        }
      };
      const callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) {
        func.apply(context, args);
      }
    };
  }

  // 窗口变化
  onResize() {
    console.log('windonw is resize');
    const h = this.el.nativeElement.querySelector('.canvas-wrap').getBoundingClientRect().height;
    const w = this.el.nativeElement.querySelector('.canvas-wrap').getBoundingClientRect().width; // 设置画布
    this.rect = this.canvas.getRect();
    if (this.rect.width / this.rect.height > w / h) {
      this.canvas.scale(w / this.rect.width * 0.9);
    } else {
      this.canvas.scale(h / this.rect.height * 0.95);
    }
    this.canvas.translate(w / 2 - this.rect.center.x, h / 2 - this.rect.center.y);
  }

  // 概化图元素事件
  onMouseEvent(event: string, node: any): void {
    if (event === 'moveInNode') {
      if (node.data != '' && (['ZZ', 'ZQ', 'gate', 'gate_out'].indexOf(node.data.type) > -1)) {
        console.log(event, node);
        this.infoShow = true;
        const yArr = [node.rotatedAnchors[0].y, node.rotatedAnchors[1].y, node.rotatedAnchors[2].y, node.rotatedAnchors[3].y];
        const featureH = _.max(yArr) - _.min(yArr);
        console.log(featureH);
        this.hoverItem.top = (node.rect.center.y - 120 - featureH / 2 + 10) + 'px';
        this.hoverItem.left = (node.rect.center.x - 76) + 'px';

        const nodeId = node.data.cid;
        this.zxData.map(item => {
          if (item.objId == nodeId) {
            this.hoverItem.alertLevel = item.alertLevel || '-';
            this.hoverItem.flow = item.flow || '-';
            this.hoverItem.limitTraffic = item.limitTraffic || '-';
            this.hoverItem.waterLevel = item.waterLevel || '-';
          }
        });
      }
    }
    if (event === 'moveOutNode') {
      this.infoShow = false;
    }
    if (event === 'node') {
      // alert(node.data.name + '被点击了');
    }
  }

  getMapData(): void {
    this.fetchService.post<any>('schedule/actualDispatchMonData/data', {manageId: '10001'}).subscribe(r => {
      this.zxData = r;
      this.fetchService.get<any>('assets/data/zxnew/1.json').subscribe(res => {
        const pens = res.pens;
        // 数据处理
        this.zxData.map(feature => {
          for (const pen of pens) {
            // 修改闸门颜色
            if (pen.data.cid == feature.objId) {
              if (feature.objType == 'ZZ' || feature.objType == 'SZY') {
                // 屏蔽ZZ和SZY这两种类型
              } else if (feature.objType == 'HH') {
                pen.image = '/yjq_web/assets/images/ght/newicons/dm' + feature.status + '.png';
              } else {
                pen.image = '/yjq_web/assets/images/ght/newicons/' + feature.objType + feature.status + '.png';
              }
            }
            // 修改q
            if (pen.data.cid == `${feature.objId}q`) {
              pen.text = feature.flow ? feature.flow + 'm³/s' : '-m³/s';
            }
            // 修改h
            if (pen.data.cid == `${feature.objId}h`) {
              pen.text = feature.waterLevel ? feature.waterLevel + 'm' : '-m';
            }
          }
        });

        if (this.canvas) {
          // 重置画布数据
          this.canvas.open({
            id: '',
            version: '',
            name: 'new空白文件',
            desc: '',
            image: '',
            userId: '',
            class: '',
            component: false,
            shared: false
          });
        } else {
          // 创建画布
          this.canvasOptions.on = this.onMouseEvent.bind(this);
          this.canvas = new Topology('zx-canvas', this.canvasOptions);
        }
        this.canvas.open(res);

        // 设置画布
        this.onResize();
      });
    });
  }

  queryGqjskll(): void {
    const year = new Date().getFullYear();
    const month = new Date().getMonth() + 1;
    const token = localStorage.token;
    const serverUrl = (window as any).environment.reportUrl;
    const link = `${serverUrl}preview?_u=wrs:干渠进水口水位流量.ureport.xml&_t=3,6&year=${year}&month=${month}&token=${token}`;
    this.gqjskllReportSrc = this.sanitizer.bypassSecurityTrustResourceUrl(link);
  }
}
